package com.group01.community.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.group01.community.entity.SysArea;
import com.group01.community.mapper.SysAreaMapper;
import com.group01.community.service.SysAreaService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 区域表 服务实现类
 * </p>
 *
 * @author guoyuan
 * @since 2025-05-01
 */
@Service
public class SysAreaServiceImpl extends ServiceImpl<SysAreaMapper, SysArea> implements SysAreaService {

    @Override
    public List<SysArea> getAreaTree() {
        return buildTree(list());
    }

    private List<SysArea> buildTree(List<SysArea> areas) {
        ArrayList<SysArea> sysAreas;
        sysAreas = (ArrayList<SysArea>) areas.stream().filter(a -> a.getParentId() == 0).collect(Collectors.toList());
        for (SysArea province : sysAreas) {
            province.setAreas(areas.stream().filter(city -> city.getParentId().equals(province.getCode())).collect(Collectors.toList()));
        }
        for (SysArea province : sysAreas) {
            List<SysArea> citys = province.getAreas();
            for (SysArea city : citys) {
                city.setAreas(areas.stream().filter(town -> town.getParentId().equals(city.getCode())).collect(Collectors.toList()));
            }
        }
        return sysAreas;
    }
}
